package ru.st.selenium;

import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;

import org.testng.*;
import org.testng.annotations.*;

import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;

import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.internal.seleniumemulation.WaitForPageToLoad;
import org.openqa.selenium.support.ui.Select;

import com.gargoylesoftware.htmlunit.WaitingRefreshHandler;

public class SearchFilm extends ru.st.selenium.pages.TestBase {
  private boolean acceptNextAlert = true;
  private StringBuffer verificationErrors = new StringBuffer();

  @Test
  public void testSearch() throws Exception {
    driver.get(baseUrl + "/php4dvd/");
    
    for (int second = 0;; second++) {
    	if (second >= 60) fail("timeout");
    	try { if (isElementPresent(By.cssSelector("div.nocover"))) break; } catch (Exception e) {}
    	Thread.sleep(1000);
    }    
    //page loaded, find film

    driver.findElement(By.id("q")).clear();
    driver.findElement(By.id("q")).sendKeys("First");
    driver.findElement(By.id("q")).sendKeys(Keys.RETURN);
    driver.findElement(By.id("q")).sendKeys(Keys.RETURN);
    driver.navigate().refresh();
    assertEquals("First", driver.findElement(By.id("q")).getAttribute("value"));
    assertEquals("My First Film", driver.findElement(By.cssSelector("div.title")).getText());
    
    driver.findElement(By.id("q")).clear();
    driver.findElement(By.id("q")).sendKeys("Second");
    driver.findElement(By.id("q")).sendKeys(Keys.RETURN);
    driver.findElement(By.id("q")).sendKeys(Keys.RETURN);
    assertEquals("Second", driver.findElement(By.id("q")).getAttribute("value"));
    
    assertEquals("No movies where found.", driver.findElement(By.cssSelector("div.content")).getText());
    driver.findElement(By.id("q")).clear();
    driver.findElement(By.id("q")).sendKeys(Keys.RETURN);
  }
  
  private boolean isElementPresent(By by) {
    try {
      driver.findElement(by);
      return true;
    } catch (NoSuchElementException e) {
      return false;
    }
  }

  private String closeAlertAndGetItsText() {
    try {
      Alert alert = driver.switchTo().alert();
      String alertText = alert.getText();
      if (acceptNextAlert) {
        alert.accept();
      } else {
        alert.dismiss();
      }
      return alertText;
    } finally {
      acceptNextAlert = true;
    }
  }
}
